/**
  mutex.c - Created by Timothy Morey on 3/20/2012.

  This file implements the interface defined in mutex.h.
*/

#ifdef __WINDOWS__
#include <Windows.h>
#else
#include <pthread.h>
#endif

#include "mutex.h"

int InitMutex(Mutex* mutex)
{
  int retval = 0;

  if(mutex)
  {
#ifdef __WINDOWS__
    mutex->Mutex = CreateMutex(0, 0, 0);
#else
    pthread_mutex_init(&mutex->Mutex, 0);
#endif
  }

  return retval;
}

int DestroyMutex(Mutex* mutex)
{
  int retval = 0;

#ifdef __WINDOWS__
  retval = CloseHandle(mutex->Mutex);
#else
  retval = 0 == pthread_mutex_destroy(&mutex->Mutex);
#endif

  return retval;
}

int GetLock(Mutex mutex)
{
#ifdef __WINDOWS__
  return WAIT_FAILED != WaitForSingleObject(mutex.Mutex, INFINITE);
#else
  return 0 == pthread_mutex_lock(&mutex.Mutex);
#endif
}

int ReleaseLock(Mutex mutex)
{
#ifdef __WINDOWS__
  return ReleaseMutex(mutex.Mutex);
#else
  return 0 == pthread_mutex_unlock(&mutex.Mutex);
#endif
}
